package springboot.example.controller;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import springboot.example.domain.*;
import springboot.example.entity.ClientType;
import springboot.example.entity.JSONResult;
import springboot.example.entity.KeyValue;
import springboot.example.entity.Student;
import springboot.example.tools.CommonUtils;
import springboot.example.tools.RoundCalculationUtil;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

@RestController
public class HelloController {

    @Autowired
    private StudentProperties studentProperties;
    @Autowired
    private RoundCalculationUtil roundCalculationUtil;
    @RequestMapping("/getStudent")
    public JSONResult<Student> getStudent(){
        Student st = new Student(studentProperties.getName(),studentProperties.getAge(),studentProperties.getAddress());
        Student st1 = new Student(studentProperties.getName(),studentProperties.getAge(),studentProperties.getAddress());
        List<Student> ss = new ArrayList<>();
        ss.add(st);
        ss.add(st1);
        JSONResult<Student> result = new JSONResult<>();
        result.setMsg("success");
        result.setCode(0);
        result.setListData(ss);
        return result;
    }

    @RequestMapping("/hello")
    public String hello() {

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String ipAddr = CommonUtils.getIpAddr(request);
        String userAgent = request.getHeader("User-Agent");
        System.err.println("ip :"+ipAddr +"client type:"+userAgent);
        ClientType requestClientType = CommonUtils.getRequestClientType(request);
        JSONObject root = null;
        try {
            root = new JSONObject();
            JSONObject student = new JSONObject();
            student.put("name",studentProperties.getName());
            student.put("age",studentProperties.getAge());
            student.put("address",studentProperties.getAddress());

            List<Student> students = new ArrayList<>();
            students.add(new Student(studentProperties.getName(),studentProperties.getAge(),studentProperties.getAddress()));
            students.add(new Student(studentProperties.getName(),studentProperties.getAge(),studentProperties.getAddress()));

            root.put("code", 0);
            root.put("client_type", requestClientType.getValue());
            root.put("student",student);
            root.put("data",new JSONArray(handleList2(students)).toString());
            root.put("msg","success");

        }catch (SecurityException e) {
            e.getStackTrace();
        } catch (Exception e) {
            System.out.print(e.getCause().toString());
            root.put("code", -1);
            root.put("result", "");
            root.put("msg","error" + e.getMessage());
        }
        return root.toString();
    }


    private <T> JSONArray handleList(List<T> data){
        JSONArray root = new JSONArray();
        try {
            root = new JSONArray();

            for (int i = 0; i < data.size(); i++) {
                T ob = data.get(i);
                root.put(new JSONObject(ob.toString()));
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return root;
    }

    private <T> String handleList2(List<T> data){
        StringBuilder listString = new StringBuilder("[");
        for (int i = 0; i < data.size(); i++) {
            T t = data.get(i);
            if (i == data.size() - 1) {
                listString.append(new JSONObject(t));
            } else {
                listString.append(new JSONObject(t)).append(",");
            }
        }
        listString.append("]");

        return listString.toString();
    }


    @RequestMapping("/hello/result")
    public String result(){

        List<KeyValue>  keyValues = null;
        try {
            keyValues = new ArrayList<>();
            List<Student> students = new ArrayList<>();
            students.add(new Student(studentProperties.getName(),studentProperties.getAge(),studentProperties.getAddress()));
            students.add(new Student(studentProperties.getName(),studentProperties.getAge(),studentProperties.getAddress()));
            HandleResultData student = new HandleResultData(students);

            keyValues.add(new KeyValue("result",student.toJsonArray()));
            keyValues.add(new KeyValue("msg","success"));
            keyValues.add(new KeyValue("code",0));


        } catch (Exception e) {
            e.printStackTrace();
            keyValues.clear();
            keyValues.add(new KeyValue("code",-1));
            keyValues.add(new KeyValue("result",""));
            keyValues.add(new KeyValue("msg","error"));

        }
        return new HandleResultData(keyValues).toJsonObject().toString() ;
    }

    /**
     *  访问方式 http://localhost/test?amount=25.568&name=ddd
     * @param amount
     * @param name
     * @return
     */
    @RequestMapping(value = "/test",method = {RequestMethod.POST,RequestMethod.GET})
    public String test(@RequestParam(value = "amount", required = true, defaultValue = "100.1111") BigDecimal amount, @RequestParam(value = "name", required = false, defaultValue = "test") String name) {
        JSONObject root = null;
        try {
            root = new JSONObject();
            BigDecimal result = roundCalculationUtil.reCalculateAmount(amount);
            DecimalFormat df = new DecimalFormat("0.00");
            root.put("code", 0);
            root.put("result", df.format(result));
            root.put("name", name);

        }catch (SecurityException e) {
            e.getStackTrace();
        } catch (Exception e) {
            System.out.print(e.getCause().toString());
            root.put("code", -1);
            root.put("result", "");
            root.put("name", "");

        }
        return root.toString();
    }

}
